package com.system.permissiondemo.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sun.tools.javac.code.Attribute;
import com.system.permissiondemo.exception.CustomizeException;
import org.thymeleaf.util.MapUtils;

import javax.validation.*;
import java.util.*;

/**
* @Description:    校验工具类
* @Author:         Joe
* @CreateDate:     2020/3/25 0:30
*/
public class BeanValidator {

    //全局校验工厂
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     * 单独校验，多类型校验，可以传入多种类型
     * @param t
     * @param groups
     * @param <T>
     * @return
     */
    public static <T>Map<String, String> validate(T t, Class... groups){
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()){
            return Collections.emptyMap();
        }else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()){
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                errors.put(violation.getPropertyPath().toString(),violation.getMessage());
            }
            return errors;
        }
    }

    /**
     * 集合校验
     * @param collection
     * @return
     */
    public static Map<String, String> validateList(Collection<?> collection){
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors;

        do {
            if (!iterator.hasNext()){
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object,new Class[0]);
        } while (errors.isEmpty());
        return errors;
    }

    /**
     * 任意对象进行校验
     * @param first
     * @param objects
     * @return
     */
    public static Map<String,String> validateObject(Object first, Object... objects){
        if (objects != null && objects.length >0){
            return validateList(Lists.asList(first,objects));
        }else {
            return validate(first,new Class[0]);
        }
    }

    public static void check(Object param)throws CustomizeException {
        Map<String,String> map = BeanValidator.validateObject(param);
        if (MapUtils.isEmpty(map)){
            throw  new CustomizeException(map.toString());
        }
    }
}
